package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: xrl
 * @Date: 2022/10/19  19:52
 * @Version 1.0
 */
@Service
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private Configuration configuration;

    @Autowired
    private ApArticleService apArticleService;

    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 成静态文件上传到minion
     *
     * @param apArticle 文章信息
     * @param content   文章内容
     */
    @SneakyThrows
    @Override
    @Async
    public void buildArticleToMinIo(ApArticle apArticle, String content) {
        //1. 非空判断  文章对象存在，且文章内容不为空
        if (StringUtils.isNotBlank(content)) {
            //2. 将文章内容通过freemarker生成html文件
            Template template = configuration.getTemplate("article.ftl");
            //数据模型
            Map<String, Object> contentDataModel = new HashMap<>();
            //添加文章内容到map，json格式
            contentDataModel.put("content", JSONArray.parseArray(content));
            //获取输出流
            StringWriter out = new StringWriter();
            //合成
            template.process(contentDataModel, out);

            //3. 把html文件上传到minio中
            InputStream in = new ByteArrayInputStream(out.toString().getBytes());
            String path = fileStorageService.uploadHtmlFile("", apArticle.getId()+ ".html", in);

            //4.修改ap_article表，保存static_url字段
            LambdaUpdateWrapper<ApArticle> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ApArticle::getId, apArticle.getId());
            updateWrapper.set(ApArticle::getStaticUrl, path);
            //调用service修改
            apArticleService.update(updateWrapper);
        }
    }
}
